# -*- coding: utf-8 -*-
'''
Module name: DATAImport

Created on 2013-3-20

@author: yangyil
'''
from SrcReader import SrcReader
import cx_Oracle
import os
import ConfigParser

class DATAImport:
    '''
    The main class of data importing.
    '''

    def __init__(self, srcPath, loginInfo, tableInfo):
        '''
        Initialize.
        '''
        self._db = cx_Oracle.connect(loginInfo)
        self._cursor = self._db.cursor()
        splitTableInfo = tableInfo.split(":")
        self._tablename = splitTableInfo[0]
        if len(splitTableInfo) > 1:
            self._colname = tableInfo.split(":")[1]
        else:
            self._colname = self.fields
        self._insertInfo = "".join(["INSERT INTO ",self._tablename," VALUES("]+[':'+str(x)+',' for x in range(1,self._colname.count(',')+2)])[:-1]+')'
        self._srcPath = srcPath
        self._config = ConfigParser.ConfigParser()
        self._confFile = "para.conf"
        self._config.read(self._confFile)
        if not self._config.has_section("STATUS"):
            self._config.add_section("STATUS")
    
    def Run(self):
        '''
        Do the importing!
        '''
        try:
            self._cursor.execute("".join(["drop table ",self._tablename]))
        except:
            pass
        self._cursor.execute("".join(["create table ",self._tablename,self._colname]))
        if os.path.isdir(self._srcPath):
            files = os.listdir(self._srcPath)
            _srcfileExtension = self._config.get('INIT', 'srcfile_extension')
            for onefile in files:
                if onefile[-len(_srcfileExtension):].lower()!= _srcfileExtension.lower():
                    continue
                filepath = os.path.join(self._srcPath,onefile)
                if os.stat(filepath).st_size == 0:
                    continue
                self._curFilePath = filepath
                self._config.set('STATUS', 'CurFilePath', filepath)
                self._config.write(open(self._confFile,'w'))
                self._srcReader = SrcReader(filepath)
                self._ImportOneFile()
        else:
            self._srcReader = SrcReader(self._srcPath)
            self._curFilePath = self._srcPath
            self._ImportOneFile()
            
    def BrkpntResume(self):
        '''
        Breakpoint resume!
        '''
        self._cursor.execute("".join(["select count(*) from tabs where table_name ='",self._tablename,"'"]))
        if not self._cursor.fetchone():
            print "There is no table named " + self._tablename + " in data base."
            return
        self._curFilePath = self._config.get('STATUS', 'CurFilePath')
        if os.path.isdir(self._srcPath):
            files = os.listdir(self._srcPath)
            beginFlag = False
            for onefile in files:
                filepath = os.path.join(self._srcPath,onefile)
                if not beginFlag:
                    if filepath != self._curFilePath:
                        continue
                    else:
                        beginFlag = True
                        self._srcReader = SrcReader(filepath)
                        CurCursor = self._config.getint("STATUS", "CurOffset")
                        self._srcReader.SetCursor(CurCursor)
                        self._ImportOneFile()
                        continue
                if onefile[-3:].lower()!= 'csv':
                    continue
                if os.stat(filepath).st_size == 0:
                    continue
                self._CurFilePath = filepath
                self._config.set('STATUS', 'CurFilePath', filepath)
                self._config.write(open(self._confFile,'w'))
                self._srcReader = SrcReader(filepath)
                self._ImportOneFile()
        else:
            self._srcReader = SrcReader(self._srcPath)
            self._ImportOneFile()
        
    def _ImportOneFile(self):
        '''
        Import the content of one file to database.
        '''
        i = 0
        _intervel = self._config.getint('INIT', 'interval')
        while not self._srcReader.isEnd():
            temp = self._ReadOneRow()
            self._InsertOneRow(temp)
            i += 1
            if i == _intervel:
                self._db.commit()
                self._config.set('STATUS', 'CurOffSet', self._srcReader.GetCursor())
                self._config.write(open(self._confFile,'w'))
                i = 0
        self._db.commit()
        self._config.set('STATUS', 'CurOffSet', self._srcReader.GetCursor())
        self._config.write(open(self._confFile,'w'))
            
    def _InsertOneRow(self, src):
        '''
        Insert one row to database.
        '''
        try:
            self._cursor.execute(self._insertInfo,src)
        except:
            pass
        
    def _ReadOneRow(self):
        '''
        Read one row  from the source file.
        '''
        return 0